package cn.volunteer.points.system.util;

import cn.volunteer.points.system.handle.ServiceErrorCode;
import cn.volunteer.points.system.handle.ServiceException;
import cn.volunteer.points.system.pojo.entity.User;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Date;
import java.util.HashMap;

/**
 * @description: 单点登录工具类
 * @author:
 * @create: 创建时间：2021-04-17
 **/
public class JWTUtils {


    /**
     * token 过期时间2h
     */
    private static final long EXPIRE_TIME = 2*60*60*1000;


    /**
     * token私钥
     */
    private static final String TOKEN_SECRET = "dabaoshu";

    /**
     * 生成token
     * @param user
     * @return
     */
    public static String getToken(User user){

        String token = null ;

        //1.过期时间
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);

        //2.私钥以及加密算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);

        //3.设置头信息
        HashMap<String, Object> head = new HashMap<>();
        head.put("type","JWT");
        head.put("alg","HS256");



        //4.附带userName和userId生成token
        token = JWT.create()
                .withHeader(head)
                .withClaim("userName",user.getUserName())
                .withExpiresAt(date)
                .sign(algorithm);

        return token ;
    }

    /**
     * 校验token是否有效
     * @param token
     * @return
     */
    public static boolean verity(String token){
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (Exception e) {
            throw new ServiceException(ServiceErrorCode.TOKEN_INVALID);
        }
    }

}
